﻿using System;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using FireStarterModeller.BO;
using Habanero.Base;
using Habanero.Base.Exceptions;
using Habanero.BO;
using Habanero.BO.ClassDefinition;
using Habanero.Faces.Base;
using Habanero.Faces.Win;

namespace FireStarterModeller.UI
{
    public class SortPropertySelectorMapper : ControlMapper
    {
        public BORelationshipMapper BoRelationshipMapper { get; private set; }

        public ExtendedTextBoxWin ExtendedTextBox
        {
            get { return (ExtendedTextBoxWin)Control; }
        }

        private ISingleRelationship _singleRelationship;
        public IFormHabanero PopupForm { get; protected set; }
        private IEditableGridControl _editableGridControl;

        public SortPropertySelectorMapper(IControlHabanero ctl, string relationshipName, bool isReadOnly, IControlFactory factory)
            : base(ctl, relationshipName, isReadOnly, factory)
        {
            ExtendedTextBox.TextBox.Enabled = false;
            ExtendedTextBox.TextBox.BackColor = Color.White;
            BoRelationshipMapper = new BORelationshipMapper(relationshipName);
            BoRelationshipMapper.RelationshipChanged += OnRelationshipChanged;
            ExtendedTextBox.Button.Click += delegate
            {
                try
                {
                    CreatePopupForm();
                    PopupForm.Closed += delegate
                                            {
                                                try
                                                {
                                                    ExtendedTextBox.TextBox.Text = Convert.ToString(GetCurrentDMSortOrder());
                                                }
                                                catch (Exception ex)
                                                {
                                                    GlobalRegistry.UIExceptionNotifier.Notify(ex, "", "Error ");
                                                }
                                            };
                    PopupForm.ShowDialog();
                }
                catch (Exception ex)
                {
                    GlobalRegistry.UIExceptionNotifier.Notify(ex, "", "Error ");
                }
            };
        }

        public override void ApplyChangesToBusinessObject()
        {

        }

        protected override void InternalUpdateControlValueFromBo()
        {
            ExtendedTextBox.TextBox.Text = Convert.ToString(GetCurrentDMSortOrder());
        }

        protected override object GetPropertyValue()
        {
            return GetCurrentDMSortOrder();
        }

        private DMSortOrder GetCurrentDMSortOrder()
        {
            if (_singleRelationship == null) return null;
            var sortOrder = _singleRelationship.GetRelatedObject();
            if(sortOrder == null)
            {
                sortOrder = new DMSortOrder();
                _singleRelationship.SetRelatedObject(sortOrder);
            }
            return (DMSortOrder)sortOrder;
        }

        protected override void SetPropertyValue(object value)
        {
            // _singleRelationship.SetRelatedObject((IBusinessObject) value);
        }

        public override IBusinessObject BusinessObject
        {
            get { return BoRelationshipMapper.BusinessObject; }
            set
            {
                IBusinessObject businessObject = BoRelationshipMapper.BusinessObject;
                BoRelationshipMapper.BusinessObject = value;
                if (BoRelationshipMapper.Relationship != null &&
                    !(BoRelationshipMapper.Relationship is SingleRelationship<DMSortOrder>))
                {
                    BoRelationshipMapper.BusinessObject = businessObject;
                    string message =
                        string.Format(
                            "The relationship '{0}' on '{1}' is not a single relationship to a 'DMSortOrder'. " +
                            "The SortPropertySelectorMapper must be mapped to a Single Relationship to a 'DMSortOrder'.",
                            PropertyName, value.ClassDef.ClassName);
                    throw new HabaneroDeveloperException(message, message);
                }
                SetBusinessObjectInternal(value);
            }
        }

        public BusinessObjectCollection<DMProperty> DMProperties { get; set; }

        public IEditableGridControl EditableGridControl
        {
            get
            {
                return _editableGridControl;
            }
        }


        private void SetBusinessObjectInternal(IBusinessObject businessObject)
        {
            _businessObject = businessObject;
            OnBusinessObjectChanged();
            UpdateIsEditable();
            UpdateControlValueFromBusinessObject();
            //AddCurrentBOPropHandlers();
            //this.UpdateErrorProviderErrorMessage();
        }

        private void UpdateIsEditable()
        {
            ExtendedTextBox.Enabled = !IsReadOnly && BusinessObject != null;
        }

        private void OnRelationshipChanged(object sender, EventArgs args)
        {
            IRelationship relationship = BoRelationshipMapper.Relationship;
            if (_singleRelationship != null) _singleRelationship.RelatedBusinessObjectChanged -= OnRelatedBusinessObjectChanged;
            _singleRelationship = relationship as ISingleRelationship;
            if (_singleRelationship != null) _singleRelationship.RelatedBusinessObjectChanged += OnRelatedBusinessObjectChanged;
        }

        private void OnRelatedBusinessObjectChanged(object sender, EventArgs args)
        {
            UpdateControlValueFromBusinessObject();
        }

        ///<summary>
        /// Shows the popup form that is displayed when the button is clicked.
        /// This popup form is used to edit the <see cref="BusinessObject"/>s that fill the combobox.
        ///</summary>
        public virtual void CreatePopupForm()
        {
            if (this.DMProperties == null)
            {
                const string message = "The DMProperties must be set first.";
                throw new HabaneroDeveloperException(message, message);
            }

            _editableGridControl = ControlFactory.CreateEditableGridControl();
            _editableGridControl.Buttons["Save"].Click += ((sender, args) => ClosePopupForm());
            _editableGridControl.Buttons["Cancel"].Click += ((sender, args) => ClosePopupForm());
            DMSortOrder dmSortOrder = GetCurrentDMSortOrder();

            _editableGridControl.BusinessObjectCollection = dmSortOrder.DMSortProperties;
            _editableGridControl.Dock = DockStyle.Fill;
            PopupForm = ControlFactory.CreateForm();
            PopupForm.Height = 200;
            PopupForm.Width = 450;
            PopupForm.Controls.Add(_editableGridControl);
            //SetupColumnLookupWithProperties(this.DMProperties, "PropertyName", _editableGridControl);
            SetupColumnLookupWithProperties(this.DMProperties, "-SortOrderPropertyName-", _editableGridControl);
        }

        private void ClosePopupForm()
        {
            try
            {
                PopupForm.Close();
            }
            catch (Exception ex)
            {
                GlobalRegistry.UIExceptionNotifier.Notify(ex, "", "Error ");
            }
        }

        private void SetupColumnLookupWithProperties(BusinessObjectCollection<DMProperty> properties, string columnName, IEditableGridControl editableGridControl)
        {
            ReadOnlyDataSetProvider readOnlyDataSetProvider = new ReadOnlyDataSetProvider(properties);
            //IUIGrid uiGrid = Habanero.BO.ClassDefinition.ClassDef.Get<DMProperty>().GetUIDef("ComboLookup").UIGrid;
            var uiDef = Habanero.BO.ClassDefinition.ClassDef.Get<DMProperty>().GetUIDef("SortOrderComboLookup");
            if (uiDef == null)
            {
                throw new HabaneroDeveloperException(
                    "The SortOrderComboLookup UIDef for DMProperty no longer exists in the ClassDef");
            }

            IUIGrid uiGrid = uiDef.UIGrid;
            DataTable dataTable = readOnlyDataSetProvider.GetDataTable(uiGrid);
            
            IDataGridViewComboBoxColumn column = (IDataGridViewComboBoxColumn)editableGridControl.Grid.Columns[columnName];
            if (column == null) return;
            column.DataSource = dataTable;
            //column.DisplayMember = "PropertyName";
            //column.ValueMember = "PropertyName";
            column.DisplayMember = "-SortOrderPropertyName-";
            column.ValueMember = "-SortOrderPropertyName-";
        }

        public void ShowPopupform()
        {
            this.PopupForm.ShowDialog();
        }
    }
}
